/*
 * @Author: dingyuwen ding_yuwen@163.com
 * @Date: 2023-02-08 18:03:18
 * @LastEditTime: 2023-04-16 11:42:34
 * @LastEditors: dingyuwen
 * @Description:
 */
import { Box, SimpleGrid } from '@chakra-ui/react';
import IAIInput from 'common/components/IAIInput';
import type { ChangeEvent, ReactNode } from 'react';
import { useMemo, useState, useTransition } from 'react';
import { useTranslation } from 'react-i18next';

import { useAppSelector } from 'app/store/storeHooks';

import ArtistItem from './ArtistItem';

export const ArtistPickerContent = () => {
  const { artist } = useAppSelector((store) => store.preset);

  const { t } = useTranslation();
  const [_, startTransition] = useTransition();
  const [searchText, setSearchText] = useState<string>('');
  const handleSearchFilter = (e: ChangeEvent<HTMLInputElement>) => {
    startTransition(() => {
      setSearchText(e.target.value);
    });
  };

  const renderArtistListItems = useMemo(() => {
    const filteredArtistListItemsToRender: ReactNode[] = [];
    const allArtistListItemsToRender: ReactNode[] = [];

    artist.forEach((a) => {
      const { id, name, avatarSrc, desc, images } = a;

      allArtistListItemsToRender.push(
        <ArtistItem key={a.id} artist={{ id, name, avatarSrc, desc, images }} />
      );

      if (
        (a.name && a.name.toLowerCase().includes(searchText.toLowerCase())) ||
        a.englishDesc.toLowerCase().includes(searchText.toLowerCase())
      ) {
        filteredArtistListItemsToRender.push(
          <ArtistItem
            key={a.id}
            artist={{ id, name, avatarSrc, desc, images }}
          />
        );
      }
    });
    return searchText !== ''
      ? filteredArtistListItemsToRender
      : allArtistListItemsToRender;
  }, [artist, searchText]);

  return (
    <Box>
      <IAIInput
        onChange={handleSearchFilter}
        label={t('common.search')}
        formControlProps={{
          display: 'flex',
          alignItems: 'center',
          gap: '4',
        }}
      />
      <SimpleGrid mt={2} columns={{ base: 2, lg: 3, xl: 4 }} spacing={4}>
        {renderArtistListItems}
      </SimpleGrid>
    </Box>
  );
};

export default ArtistPickerContent;
